<template>
  <el-container style="flex-direction: column; height: 100vh;">
    <!-- 顶部栏 -->
    <HeaderComponent :userInfo="this.userInfo" />

    <!-- 主内容区 -->
    <el-container style="flex-direction: row; height: 100vh;">
      <!-- 侧边栏 -->
      <SidebarComponent />

      <!-- 主内容 -->
      <el-main>
        <!-- 顶部功能区 -->
        <div class="toolbar">
          <el-card style="width: 100%; border-color: gray;">
            <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete"
              style="margin-left: 0px">批量删除</el-button>
            <el-input v-model="searchKeyword" placeholder="请输入业主姓名" style="width: 200px; margin-left: 100px"
              clearable />
            <el-select v-model="statusKeyword" placeholder="请选择状态" style="width: 120px; margin-left: 20px" clearable>
              <el-option label="全部" value=""></el-option>
              <el-option label="待审核" value="1"></el-option>
              <el-option label="未到访" value="2"></el-option>
              <el-option label="已到访" value="3"></el-option>
              <el-option label="已拒绝" value="4"></el-option>
              <el-option label="申请过期" value="5"></el-option>
            </el-select>
            <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" style="margin-left: 20px" value-format="yyyy-MM-dd hh:mm:ss" />
            <el-button type="primary" icon="el-icon-search" @click="getVisitors" style="margin-left: 20px">查
              询</el-button>
          </el-card>
        </div>

        <!-- 访客列表 -->
        <el-table :data="visitors" style="width: 100%;" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" header-align="center" align="center"></el-table-column>
          <el-table-column prop="visitorName" label="姓名" header-align="center" align="center"></el-table-column>
          <el-table-column prop="visitorImage" label="照片" width="120" header-align="center" align="center">
            <!-- <template #default="scope">
              <el-image style="width: 80px; height: 80px; border-radius: 4px;" :src="scope.row.visitorImage"
                :preview-src-list="[scope.row.visitorImage]" fit="cover" />
            </template> -->
          </el-table-column>
          <el-table-column prop="visitorPhone" label="联系方式" header-align="center" align="center"></el-table-column>
          <el-table-column prop="username" label="业主" header-align="center" align="center"></el-table-column>
          <el-table-column prop="destination" label="去向" header-align="center" align="center"></el-table-column>
          <el-table-column label="到访时间" header-align="center" align="center">
            <template #default="scope">
              {{ scope.row.arriveTime }} 到 {{ scope.row.leaveTime }}
            </template>
          </el-table-column>
          <el-table-column prop="toDo" label="到访目的" header-align="center" align="center"></el-table-column>
          <el-table-column prop="state" label="状态" header-align="center" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.state === 1 ? 'warning' : 'success'">
                {{ getStateText(scope.row.state) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100px" header-align="center" align="center">
            <template #default="scope">
              <el-button size="mini" type="primary" @click="handleEdit(scope.row)">详 情</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-pagination style="margin-top: 20px; text-align: center;" background
          layout="total, sizes, prev, pager, next, jumper" :total="this.total" :page-sizes="[10, 20, 50, 100]"
          :page-size="this.pageSize" :current-page="this.page" @size-change="handleSizeChange"
          @current-change="handlePageChange" />

        <!-- 编辑预约弹窗 -->
        <el-dialog title="编辑预约" :visible.sync="editDialogVisible" width="500px">
          <el-form :model="currentVisitor" label-width="80px">
            <el-form-item label="业主姓名">
              <el-input v-model="currentVisitor.username"></el-input>
            </el-form-item>
            <el-form-item label="访客姓名">
              <el-input v-model="currentVisitor.visitorName"></el-input>
            </el-form-item>
            <el-form-item label="到访时间">
              <el-date-picker v-model="currentVisitor.arriveTime" type="datetime" placeholder="选择到访时间" />
            </el-form-item>
            <el-form-item label="离开时间">
              <el-date-picker v-model="currentVisitor.leaveTime" type="datetime" placeholder="选择到访时间" />
            </el-form-item>

            <!-- 访客照片 -->
            <el-form-item label="访客照片">
              <el-upload style="text-align:left" ref="pictureUpload" action="#" :list-type="'picture-card'"
                :auto-upload="false" :on-change="handleChange" :file-list="initialFileList">
                <i slot="default" class="el-icon-plus"></i>
                <div slot="file" slot-scope="{file}">
                  <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
                  <span class="el-upload-list__item-actions">
                    <!-- 放大查看缩略图 -->
                    <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                      <i class="el-icon-zoom-in"></i>
                    </span>
                    <!-- 删除缩略图 -->
                    <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                      <i class="el-icon-delete"></i>
                    </span>
                  </span>
                </div>
              </el-upload>
              <el-dialog :visible.sync="dialogVisiblePicture" :modal="false">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>

            <el-form-item label="目的地">
              <el-input v-model="currentVisitor.destination" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="事由">
              <el-input v-model="currentVisitor.toDo" type="textarea"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="currentVisitor.state" placeholder="选择状态" clearable>
                <el-option label="申请中" :value=1 />
                <el-option label="未到访" :value=2 />
                <el-option label="已到访" :value=3 />
                <el-option label="拒绝到访" :value=4 />
                <el-option label="申请过期" :value=5 />
              </el-select>
            </el-form-item>
            <el-form-item label="邀请码">
              <el-input v-model="currentVisitor.invitationCode"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSaveEdit">保存</el-button>
          </span>
        </el-dialog>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import HeaderComponent from '@/components/property_components/PropertyHeader.vue';
import SidebarComponent from '@/components/property_components/PropertySidebar.vue';
import { parseJwt } from '@/utils/parseJWT';
import service from '@/utils/request';

export default {
  components: {
    HeaderComponent,
    SidebarComponent,
  },
  data() {
    return {
      userInfo: {},
      selectedVisitorIds: [], // 选中的访客
      dateRange: [], // 日期范围
      statusKeyword: '', // 状态搜索关键词
      searchKeyword: '', // 搜索关键词
      page: 1, // 当前页码
      pageSize: 10, // 每页显示条数

      visitors: [],
      total: 0,
      currentVisitor: {}, // 当前编辑的访客数据
      editDialogVisible: false, // 编辑预约弹窗显示状态

      //图片上传缩略图所需的属性
      dialogImageUrl: '',
      dialogVisiblePicture: false,
      disabled: false,
      //  图片上传文件列表
      pictureFile: {},
      initialFileList: [],
      updateImage: false,
    };
  },
  mounted() {
    this.userInfo = parseJwt(localStorage.getItem('token')).payload;
    this.getVisitors();
  },
  methods: {
    //获取所有访客
    getVisitors() {
      service.get('/api/admin/apply/getAllApply', {
        params: {
          searchKeyword: this.searchKeyword,
          statusKeyword: this.statusKeyword,
          startTime: this.dateRange ? this.dateRange[0] : '',
          endTime: this.dateRange ? this.dateRange[1] : '',
          page: this.page,
          pageSize: this.pageSize,
        }
      })
        .then((result) => {
          result = result.data;
          this.visitors = result.data.rows || [];
          this.total = result.data.total;
          console.log(this.visitors);
        })
        .catch((error) => {
          console.error(error);
        });
    },

    // 批量删除
    handleBatchDelete() {
      if (this.selectedVisitorIds.length === 0) {
        this.$message.warning('请选择要删除的访客');
        return;
      }
      this.$confirm('确认删除选中的访客记录?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        const ids = this.selectedVisitorIds;
        service.post('/api/user/apply/deleteApply', ids)
          .then((result) => {
            result = result.data;
            if (result.code == 1) {
              this.$message.success('批量删除成功');
              this.getVisitors(); // 刷新数据
            } else {
              this.$message.error(result.msg);
            }
          })
          .catch((error) => {
            this.$message.error(error);
          })
      });
    },

    // 处理编辑
    handleEdit(row) {
      this.currentVisitor = row;
      this.editDialogVisible = true;

      this.initialFileList = [];
      this.initialFileList.push({ url: this.currentVisitor.visitorImage });
      this.updateImage = false;
    },

    // 保存编辑
    handleSaveEdit() {
      const index = this.visitors.findIndex((v) => v.id === this.currentVisitor.id);
      this.visitors.splice(index, 1, this.currentVisitor);
      this.editDialogVisible = false;
      this.$message.success('修改成功');
    },

    // 根据状态返回状态文本
    getStateText(state) {
      switch (state) {
        case 1: return '申请中';
        case 2: return '未到访';
        case 3: return '已到访';
        case 4: return '拒绝到访';
        case 5: return '申请过期';
        default: return '未知状态';
      }
    },

    // 处理选中项变化
    handleSelectionChange(selection) {
      this.selectedVisitorIds = [];
      console.log("selection:", selection);
      // 提取selection中每个对象的id属性
      selection.forEach(item => {
        this.selectedVisitorIds.push(item.id);
      });
    },

    // 处理页码变化
    handlePageChange(page) {
      this.page = page;
      this.getVisitors();
    },

    // 处理每页显示条数变化
    handleSizeChange(size) {
      console.log(size);
      this.pageSize = size;
      this.page = 1; // 重置为第一页
      this.getVisitors();
    },



    // 图片缩略图放大查看
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisiblePicture = true;
    },

    //图片缩略图组件选择图片后事件
    handleChange(file, fileList) {
      console.log(file, fileList);
      if (fileList.length > 1) {
        this.$message({ type: 'error', message: '只能上传一张图片' });
        this.handleRemove(file);
        console.log(file, fileList);
        return;
      }
      this.pictureFile = file;
    },
    //图片缩略图删除
    handleRemove(file) {
      console.log(file);
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['uid'] == file.uid) {
          uploadFiles.splice(i, 1)
        }
      }
      this.updateImage = true;
    },
  },

};
</script>

<style scoped>
.toolbar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}
</style>